/**
 * 主页
 * @author 许明浩 微信: muaiyuese
 */
import Layout from "@/components/layout";
import Banner from "./components/Banner";
import AnimatingNumbers from "./components/AnimatingNumbers";
import NoticeBar from "./components/NoticeBar";
import CardList from "./components/CardList";
import { useRequest } from "taro-hooks";
import { ApiGetPageData } from "./api";
import Skeleton from "./skeleton-loading";
import Taro, { usePullDownRefresh } from "@tarojs/taro";
import { useRef, useState } from "react";

const Index = () => {
  const layoutRef = useRef<any>();
  /**
   * 请求页面数据
   */
  // 初次加载才显示骨架屏，避免每次下拉页面闪烁
  const [pageFirstLoading, setPageFirstLoading] = useState(true);
  const {
    data: res,
    loading,
    refresh,
    params: {},
  } = useRequest(ApiGetPageData, {
    onFinally: () => {
      setPageFirstLoading(false);
    },
    onError: (e: any) => {
      layoutRef?.current?.setServiceError(true, e?.msg);
    },
  });
  const { data = {} } = res || {};

  /**
   * 小程序下下拉刷新
   */
  usePullDownRefresh(() => {
    refresh();
    setTimeout(() => {
      Taro.stopPullDownRefresh();
    }, 1000);
  });

  return (
    <Layout
      ref={layoutRef}
      noheader
      loading={pageFirstLoading}
      loadingSlot={<Skeleton />}
      disableDict
    >
      {
        /**
         * 海报
         */
        <Banner />
      }
      {
        /**
         * 公告栏
         */
        <NoticeBar />
      }
      {
        /**
         * 数字动画
         */
        <AnimatingNumbers />
      }
      {
        /**
         * 商品卡片
         */
        <CardList data={data?.cardList} />
      }
    </Layout>
  );
};

export default Index;
